package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsStorageMapper;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsAdminStorageService;
import com.qf.util.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author YDW
 * projectName:shop-manage
 * time:2022/5/21 17:02
 * description:
 */
@Service
public class DtsAdminStorageServiceImpl implements DtsAdminStorageService {

    @Autowired
    DtsStorageMapper storageMapper;

    @Override
    public IPage<DtsStorage> queryPage(Integer page, Integer limit, String sort, String order, String key, String name) {

        IPage<DtsStorage> ipage=new Page<>(page,limit);
        QueryWrapper qw=new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            qw.like("`key`",key);
        }
        if(!StringUtils.isEmpty(name)){
            qw.like("name",name);
        }
        if(!StringUtils.isEmpty(sort)&&!StringUtils.isEmpty(order)){
            if(order.equals("desc")){
                qw.orderByDesc(sort);
            }else {
                qw.orderByAsc(sort);
            }
        }
        storageMapper.selectPage(ipage,qw);
        return ipage;
    }
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;


    @Override
    public DtsStorage add(byte[] bytes, String key,String name,Integer size,String type) throws Exception {

        //上传图片到阿里云
        String url = AliyunOSSUtil.uploadImage(endpoint, accessKeyId, accessKeySecret, bucketName, key, bytes);
        //将图片保存到数据库
        DtsStorage dtsStorage=new DtsStorage();
        dtsStorage.setAddTime(new Date());
        dtsStorage.setDeleted(false);
        dtsStorage.setName(name);
        dtsStorage.setUpdateTime(new Date());
        dtsStorage.setKey(key);
        dtsStorage.setType(type);
        dtsStorage.setSize(size);
        dtsStorage.setUrl(url);
        storageMapper.insert(dtsStorage);
        return dtsStorage;


    }

    @Override
    public void delete(DtsStorage dtsStorage) {


        //删除数据库的记录
        storageMapper.deleteById(dtsStorage.getId());

        //删除阿里云oss上的文件
        AliyunOSSUtil.deleteFile(endpoint,accessKeyId,accessKeySecret,bucketName,dtsStorage.getKey());


    }

    @Override
    public DtsStorage update(DtsStorage dtsStorage) {
        dtsStorage.setUpdateTime(new Date());
        storageMapper.updateById(dtsStorage);
        return dtsStorage;
    }
}
